package com.mgface.eth.tool;

import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;

import java.io.IOException;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project eth
 * @create 2018-06-29 12:48
 * @since <a href="https://github.com/ipfs/java-ipfs-api">参考链接</a>
 * @desc 借助IPFS来实现swarm功能
 **/
public class IpfsFile {
	public static String add(String data) throws IOException {
		IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001");
		NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper(data.getBytes());
		MerkleNode hash = ipfs.add(file).get(0);
		return hash.hash.toString();
	}

	public static String get(String hash) throws IOException {
		IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001");
		MerkleNode md = new MerkleNode(hash);
		byte[] data = ipfs.cat(md.hash);
		return new String(data);
	}

	public static void main(String[] args) throws IOException{
		String hash = add("alib");
		System.out.println(hash);
		String rawData = get(hash);
		System.out.println(rawData);
	}

}
